import axios from "axios";
import qs from 'qs';
import { notification } from 'ant-design-vue';

import {useUserStore} from '@/store/userStore'



export const instance = axios.create({
  baseURL: '/api',
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    "Load-Balancer": import.meta.env.VITE_APP_LOCAL_IP
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  }
});

/*
*请求前拦截
*用于处理需要请求前的操作
*/
instance.interceptors.request.use(
  config => {
    var token = useUserStore().token;
    if (token) {
      config.headers['token'] = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
/*
*请求响应拦截
*用于处理数据返回后的操作
*/
instance.interceptors.response.use(
  response => {
    return new Promise((resolve, reject) => {
      const res = response.data;
      if (response.config.responseType == 'blob') {
        resolve(response);
      } else if (typeof res != 'object' || !('result' in res)) {
        resolve(response);
      } else if (res.result === 200) {
        resolve(res);
        // token过期
      } else if (res.result == 401) {
        notification.warning({
          message: '提示',
          description: "用户登陆过期，请重新登陆"
        });
        const userStore = useUserStore();
        userStore.logout();
      } else {
        reject(res)
      }
    })
  },
  error => {
    //断网处理或者请求超时
    if (!error.response) {
      //请求超时
      if (error.message.includes("timeout")) {
        notification.error({
          message: '提示',
          description: "请求超时，请检查互联网连接"
        });
      } else {
        //断网，可以展示断网组件
        notification.error({
          message: '提示',
          description: "请检查网络是否已连接"
        });
      }
      return;
    }
    const status = error.response.status;
    notification.error({
      message: '提示',
      description: error.response.data.msg
    });
    return Promise.reject(error);
  }
);
/*
*get方法，对应ApiGet请求
*@param {String} url [请求的url地址]
*@param {Object} params [请求时候携带的参数]
*/
export function ApiGet(url, params) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'get',
      params: params,
      withCredentials: true, //允许跨域携带cookit
    }).then(res => {
      resolve(res);
    }).catch(err => {
      if (err.data) {
        notification.error({
          message: '提示',
          description: err.data
        });
      }
      reject(err);
    });
  });
}
/*
*post方法，对应ApiPost请求
*@param {String} url [请求的url地址]
*@param {Object} params [请求时候携带的参数]
*/
export function ApiPost(url, params, noError = false) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'post',
      data: params,
      withCredentials: true, //允许跨域携带cookit
    }).then(res => {
      resolve(res);
    }).catch(err => {
      if (err.data && !noError) {
        notification.error({
          message: '提示',
          description: err.data
        });
      }
      reject(err);
    });
  });
}

/*
*post方法，对应ApiPostForm请求
*@param {String} url [请求的url地址]
*@param {Object} params [请求时候携带的参数]
*/
export function ApiPostForm(url, params) {
  return new Promise((resolve, reject) => {
    instance({
      url,
      method: 'post',
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: qs.stringify(params),
      responseType: 'json',
      withCredentials: true, //允许跨域携带cookit
    }).then(res => {
      resolve(res);
    }).catch(err => {
      if (err.data) {
        notification.error({
          message: '提示',
          description: err.data
        });
      }
      reject(err);
    });
  });
}

/** 
*ApiPostFile方法，导入文件
*/
export function ApiPostFile(url, params) {
  return new Promise((resolve, reject) => {
    instance.post(url, params, {
      'Content-Type': 'multipart/form-data'
    }).then(res => {
      resolve(res);
    }).catch(err => {
      if (err.msg) {
        notification.error({
          message: '提示',
          description: err.msg
        });
      }
      reject(err);
    });
  });
}

/**
*DownFile方法，导出、下载文件
*/
export function ApiDownGet(url, params = {}, filename) {
  instance({
    url,
    method: 'get',
    data: params,
    responseType: 'blob',
  }).then(res => {
    if(!filename) {
      filename = res.headers['content-disposition']?.split('fileName=')[1];
    }
    var blob = new Blob([res.data])
    var downloadElement = document.createElement('a');
    var href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = filename || '思维导图.md'; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}

/**
*DownFile方法，导出、下载文件
*/
export function ApiDownPost(url, params = {}, filename) {
  instance({
    url,
    method: 'post',
    data: params,
    responseType: 'blob',
  }).then(res => {
    if(!filename) {
      filename = res.headers['content-disposition'].split('fileName=')[1];
    }
    var blob = new Blob([res.data])
    var downloadElement = document.createElement('a');
    var href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = filename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}

/**
 * 预览POST图片，获取路径
 * **/
export async function ApiPostImg(url, params = {}) {
  let res = await instance({
    url,
    method: 'post',
    data: params,
    responseType: 'blob',
  })
  // 抛出异常，并直接结束当前函数
  if(res.data.size == 0) {
    throw new Error("返回图片size=0");
  }
  let blob = new Blob([res.data])
  let downloadElement = document.createElement('a');
  let href = window.URL.createObjectURL(blob); //创建下载的链接
  return href;
}
